//
//  ZMOAuthViewController.swift
//  ZMWeiboSwift
//
//  Created by pg on 2017/7/24.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit

import SVProgressHUD

let OAuthKey = "1532762256"
let redirect_uri = "http://www.itcast.cn/"
let AppSecret = "16e596ce951b87e7260a7dbf6281be19"



class ZMOAuthViewController: UIViewController ,UIWebViewDelegate {

    //修改当前控制器的跟控制器为webview
    let webView = UIWebView()
    
    override func loadView() {
        
       view = webView
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNav()
        
        showLoginView()
        
        webView.delegate = self
        
        
        
    }
    //设置导航控制器
    func setupNav(){
    
        self.navigationItem.title = "微博登录"
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancleClick))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillClick))
        
    }
    //取消按钮单击事件
    func cancleClick() -> Void {
        
    }
    //自动填充按钮单击事件
    func autoFillClick() -> Void {
        
    //    let jsStr = "var btn = document.getElementsByClassName('WB_btn_login formbtn_01')[0]; btn.onclick = function test(){window.location.href = 'http://www.baidu.com'};"
        
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '13817759295';document.getElementById('passwd').value = 'ming0503';document.getElementById('passwd').focus();")
        
    }
   func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    
        if request.url?.absoluteString.hasPrefix(redirect_uri) == true{
            
            if let query = request.url?.query, query.hasPrefix("code=") {
                //截取授权吗
                let code = query.substring(from: "code=".endIndex)
                //根据授权吗获取令牌(通过viewModel获取)
                // //通过code授权吗获取令牌(AccessToKen)
                
                ZMUserAccountViewModel.sharedViewModel.requestAccessToKen(code: code, callBack: { (isSuccess:Bool) in
                    
                    if isSuccess{
                        print("登录陈宫")
                        //登录成功
                        self.dismiss(animated: false, completion: { 
                            //登录成功,要切换window的根控制器,在这里发送通知,在appdelegate中统一进行跟控制器切换
                            NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotificationName), object: self)
                        })
                    }else{
                        //登录失败
                        
                    }
                    
                })
            }else{
                //点击取消授权,,
                self.dismiss(animated: true, completion: nil)
            }
            //如果返回false 会执行webview加载失败的代理方法
            return false
        }
       return true
    }
    
    //webview 已经开始接在
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //webview 加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //webview 加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    //显示微博登录界面(第三方登录界面)
    func showLoginView() -> Void {
        
      //kay1532762256;
      
      
       //设置请求地址
        let url = URL.init(string: "https://api.weibo.com/oauth2/authorize?client_id=\(OAuthKey)&redirect_uri=\(redirect_uri)")
        
        webView.loadRequest(URLRequest(url: url!))
        
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
